package com.haozhen.demo1;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.*;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;


/**
 * @author haozhen
 * @email haozh@ync1.com
 * @date 2021/2/7  19:23
 */
public class WordCountJavaBatch {

    public static void main(String[] args) {
        String inputPath = "data/input/hello.txt";
        String output = "data/output";

        ExecutionEnvironment executionEnvironment =
                ExecutionEnvironment.createCollectionsEnvironment();

        DataSource<String> stringDataSource = executionEnvironment.readTextFile(inputPath);

        FlatMapOperator<String, Tuple2<String, Integer>> stringTuple2FlatMapOperator = stringDataSource.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String text, Collector<Tuple2<String, Integer>> collector) throws Exception {
                String[] s = text.split(" ");
                for (String s1 : s) {
                    Tuple2<String, Integer> stringIntegerTuple2 = new Tuple2<>(s1, 1);
                    collector.collect(stringIntegerTuple2);
                }
            }
        });

        UnsortedGrouping<Tuple2<String, Integer>> tuple2UnsortedGrouping = stringTuple2FlatMapOperator.groupBy(0);

        AggregateOperator<Tuple2<String, Integer>> sum = tuple2UnsortedGrouping.sum(1);

        sum.writeAsCsv(output);

        try {
            executionEnvironment.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
